<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 目录树 -->
      <el-col
        :lg="4"
        :md="5"
        :sm="6"
        :xs="24"
        class="mb-[12px] !pr-0"
        v-if="showTree"
      >
        <eamassetmodel-tree
          v-model="searchParam.assetTypeId"
          @node-click="search"
        />
      </el-col>
      <el-col
        :lg="showTree ? 20 : 24"
        :md="showTree ? 19 : 24"
        :sm="showTree ? 18 : 24"
        :xs="24"
      >
        <div class="search-container">
          <el-form :model="searchParam" :inline="true" label-width="78px">
            <el-form-item label="使用部门">
              <SelectOriganizationDangerGrant
                @change="(ids:string) => getSelectIds(ids, '使用部门')"
                :isCheckStrictly="true"
                :isMultiple="false"
                :disabled="false"
                :data="dataObject('使用部门')"
                :selectData="searchParam.usingDepartmentId"
              />
            </el-form-item>
            <el-form-item label="检具编号">
              <el-input
                v-model="searchParam.assetCode"
                placeholder="请输入检具编号"
                clearable
                @keyup.enter="search"
              />
            </el-form-item>
            <el-form-item label="器具名称">
              <el-input
                v-model="searchParam.assetName"
                placeholder="请输入器具名称"
                clearable
                @keyup.enter="search"
              />
            </el-form-item>
            <el-form-item label="规格/型号">
              <el-input
                v-model="searchParam.assetSpecification"
                placeholder="请输入规格/型号"
                clearable
                @keyup.enter="search"
              />
            </el-form-item>
            <!-- <el-form-item label="位置">
              <el-tree-select
                placeholder="请输入位置"
                filterable
                v-model="searchParam.locationId"
                :data="locationInfoTree"
                node-key="id"
                clearable
                :props="{ label: 'locationName', children: 'nodes' }"
                check-strictly
                :render-after-expand="false"
              />
            </el-form-item> -->
            <el-form-item label="器具状态">
              <el-select
                v-model="searchParam.assetStatus"
                placeholder="请选择器具状态"
                @keyup.enter="search"
                clearable
              >
                <el-option
                  v-for="item in dictionaryStore.filterDictList(
                    'mtAssetStatus'
                  )"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="管理部门">
              <SelectOriganizationDangerGrant
                @change="(ids:string) => getSelectIds(ids, '管理部门')"
                :isCheckStrictly="true"
                :isMultiple="false"
                :disabled="false"
                :data="dataObject('管理部门')"
                :selectData="searchParam.manageDepartmentId"
              />
            </el-form-item>
            <el-form-item label="制造工厂">
              <el-select
                v-model="searchParam.makerId"
                placeholder="请选择制造工厂"
                clearable
              >
                <el-option
                  v-for="item in makerList"
                  :key="`${item.id}`"
                  :label="`${item.makerCode}-${item.makerName}`"
                  :value="`${item.id}`"
                />
              </el-select>
            </el-form-item> -->
            <el-form-item label="待检定日期">
              <el-date-picker
                v-model="searchParam.nextCheckDateSearch"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD HH:mm:ss"
                @change="getcreateTime"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="search"
                ><i-ep-search />搜索</el-button
              >
              <el-button @click="reset"><i-ep-refresh />重置</el-button>
              <el-button @click="handelTree" type="primary"
                ><i-ep-location />目录树</el-button
              >
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never" class="table-container">
          <template #header>
            <el-button type="success" plain @click="openDialog()"
              ><i-ep-plus />新增</el-button
            >

            <el-button type="primary" style="display: none"
              >打印二维码</el-button
            >
            <el-button type="success" @click="excelBoxOpen">导入</el-button>
            <el-button
              @click="
                useDownload('/eam/mtAssetInfo/export', '器具台账', searchParam)
              "
            >
              <template #icon><i-ep-download /></template>导出</el-button
            >
            <el-button
              type="danger"
              plain
              :disabled="ids.length === 0"
              @click="handleTableDelete()"
              ><i-ep-delete />删除</el-button
            >
            <el-dialog
              :close-on-click-modal="false"
              title="量检具数据导入"
              v-model="excelBox"
              width="555px"
              @close="closeImportDialog"
            >
              <div style="margin-top: 10px">
                <input
                  class="crop-input"
                  :key="uploadKey"
                  type="file"
                  ref="onload_exl"
                  @change="getfilepath"
                />
                <el-button
                  @click="upload"
                  :disabled="uploadBtn"
                  style="cursor: pointer"
                  >上传</el-button
                >
              </div>
            </el-dialog>
            <el-dialog
              :close-on-click-modal="false"
              title="量检具数据导入异常信息"
              v-model="resultModel"
              width="555px"
              @close="closeMsgDialog"
            >
              <el-table
                :data="msgTableData"
                highlight-current-row
                border
                style="max-height: 500px"
              >
                <el-table-column
                  prop="row"
                  label="行号"
                  width="100%"
                  align="center"
                >
                  <template #default="scope">
                    第{{ scope.row.row }}行
                  </template>
                </el-table-column>
                <el-table-column
                  prop="type"
                  label="错误/警告"
                  width="100%"
                  align="center"
                >
                  <template #default="scope">
                    <el-tag
                      :type="scope.row.type === 'error' ? 'danger' : 'warning'"
                    >
                      {{ scope.row.type === "error" ? "错误" : "警告" }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="error" label="信息" />
              </el-table>
            </el-dialog>
          </template>

          <el-table
            ref="dataTableRef"
            v-loading="loading"
            :data="tableData"
            highlight-current-row
            border
            @selection-change="handleSelectionChange"
            @sort-change="onTableSortChanged"
          >
            <el-table-column type="selection" width="55" align="center" />

            <el-table-column
              sortable
              label="检具编号"
              prop="assetCode"
              min-width="120"
              show-overflow-tooltip
            />
            <el-table-column
              sortable
              label="企业编号"
              prop="enterpriseCode"
              min-width="120"
              show-overflow-tooltip
            />
            <el-table-column
              sortable
              label="器具名称"
              prop="assetName"
              min-width="120"
              show-overflow-tooltip
            />
            <el-table-column
              label="器具类型"
              prop="assetTypeCode"
              min-width="180"
              sortable
              show-overflow-tooltip
            >
              <template #default="scope">
                {{ scope.row.assetTypeName }}
              </template>
            </el-table-column>
            <el-table-column
              sortable
              label="器具状态"
              prop="assetStatus"
              min-width="120"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                {{ useDictionary("mtAssetStatus", scope.row.assetStatus) }}
              </template>
            </el-table-column>
            <el-table-column
              label="规格/型号"
              prop="assetSpecification"
              min-width="150"
              sortable
              show-overflow-tooltip
            />
            <el-table-column
              label="准确度等级"
              prop="accuracyLevel"
              min-width="120"
              sortable
              show-overflow-tooltip
            />
            <!-- <el-table-column
              sortable
              label="品牌型号"
              prop="assetModelNo"
              min-width="120"
              show-overflow-tooltip
            >
              <template #default="scope">
                {{ scope.row.assetBrandName
                }}{{ scope.row.assetBrandName ? "-" : ""
                }}{{ scope.row.assetModelNo }}
              </template>
            </el-table-column> -->
            <!-- <el-table-column
              sortable
              label="测量范围"
              prop="measuringRange"
              min-width="120"
              show-overflow-tooltip
              align="center"
            /> -->
            <!-- <el-table-column
              sortable
              label="精度"
              prop="measuringAccuracy"
              min-width="90"
              show-overflow-tooltip
              align="center"
            >
            </el-table-column> -->
            <el-table-column
              sortable
              label="分度值/分辨力"
              prop="measuringDivision"
              min-width="150"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column
              label="器具属性"
              prop="assetAttribute1"
              min-width="120"
              sortable
              show-overflow-tooltip
            />
            <el-table-column
              label="制造工厂"
              prop="makerName"
              min-width="150"
              sortable
              show-overflow-tooltip
            />
            <el-table-column
              sortable
              label="表头编号"
              prop="headerNumber"
              min-width="120"
              show-overflow-tooltip
            />
            <el-table-column
              sortable
              label="出厂编号"
              prop="manufactureCode"
              min-width="120"
              show-overflow-tooltip
            />
            <el-table-column
              sortable
              label="检具图号"
              prop="drawingNumber"
              min-width="120"
              show-overflow-tooltip
            />
            <el-table-column
              sortable
              label="入账日期"
              prop="accountDate"
              min-width="120"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                {{
                  scope.row.accountDate && scope.row.accountDate != null
                    ? dayjs(scope.row.accountDate).format("YYYY-MM")
                    : ""
                }}
              </template>
            </el-table-column>

            <el-table-column
              sortable
              label="管理类别"
              prop="measuringType"
              min-width="120"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                {{
                  useDictionary("EquipmentCategory", scope.row.measuringType)
                }}
              </template>
            </el-table-column>
            <el-table-column
              sortable
              label="检定周期"
              prop="checkPeriod"
              min-width="110"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column
              sortable
              label="检定到期日"
              prop="nextCheckDate"
              min-width="180"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                {{
                  scope.row.nextCheckDate
                    ? dayjs(scope.row.nextCheckDate).format("YYYY-MM-DD")
                    : ""
                }}
              </template>
            </el-table-column>
            <el-table-column
              sortable
              label="使用日期"
              prop="usingDate"
              min-width="120"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                {{
                  scope.row.usingDate
                    ? dayjs(scope.row.usingDate).format("YYYY-MM-DD")
                    : ""
                }}
              </template>
            </el-table-column>
            <el-table-column
              sortable
              label="使用部门"
              prop="usingDepartmentName"
              min-width="120"
              show-overflow-tooltip
            />
            <el-table-column
              sortable
              label="使用人"
              prop="usingPersonName"
              min-width="120"
              show-overflow-tooltip
            />
            <el-table-column
              sortable
              label="备注"
              prop="remarks"
              min-width="120"
              show-overflow-tooltip
            />

            <el-table-column
              sortable
              label="检定地点"
              prop="checkPlace"
              min-width="120"
              show-overflow-tooltip
            />
            <el-table-column
              sortable
              label="检定人"
              prop="checkPerson"
              min-width="120"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column
              sortable
              label="订货单号"
              prop="orderNumber"
              min-width="120"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column
              sortable
              label="是否是固定资产"
              prop="isFixedAsset"
              min-width="150"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                {{ scope.row.isFixedAsset === 1 ? "是" : "否" }}
              </template>
            </el-table-column>
            <el-table-column
              sortable
              label="U9编码"
              prop="fixedAssetCode"
              min-width="150"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column
              sortable
              label="器具位置"
              prop="locationName"
              min-width="120"
              show-overflow-tooltip
            />

            <el-table-column
              fixed="right"
              label="操作"
              width="240"
              align="center"
            >
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="openDialogdetail(scope.row)"
                  ><i-ep-search />
                  查看
                </el-button>
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="openDialog(scope.row)"
                  ><i-ep-edit />编辑</el-button
                >
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="deleteItem(scope.row.id)"
                  ><i-ep-delete />删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            :background="true"
            :current-page="pageable.pageNum"
            :page-size="pageable.pageSize"
            :page-sizes="[10, 25, 50, 100]"
            :total="pageable.total"
            layout="total, sizes, prev, pager, next, jumper"
            class="mt-[20px]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-card>

        <eamassetinfo-edit
          :visible="addDialog.visible"
          :title="addDialog.title"
          :data="addDialog.data"
          :assetTypeIdTree="assetTypeIdTree"
          @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
          :is-readonly="addDialog.readvisible"
          @change-visible="changeVisible"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { filterOrder } from "@/utils/commonHooks";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import dayjs from "dayjs";
defineOptions({
  name: "EAMmtAssetInfo",
  inheritAttrs: false,
});

// 目录树显隐
const showTree = ref(true);
const handelTree = () => {
  showTree.value = !showTree.value;
};

// 请求参数
const requestApi = "/eam/mtAssetInfo/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = reactive({
  sort: {
    column: "",
    orderBy: "",
  },
});

// 初始化搜索参数数据
const searchParamInit = {
  assetName: "",
  assetCode: "",
  assetTypeId: "",
  locationId: "",
  usingDepartmentId: "",
  assetStatus: "",
  manageDepartmentId: "",
  checkPerson: "",
  nextCheckDateSearch: [],
  nextCheckDateStart: "",
  nextCheckDateEnd: "",
  assetSpecification: "",
};

const deleteParam = {
  api: "/eam/mtAssetInfo/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});
// 排序
// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  console.log(prop, order);

  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}
// 监听页面 initParam 改化，重新获取表格数据
watch(() => initParam, getTableList, { deep: true });
const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/eam/mtAssetInfo/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开资产台账表单弹窗 */
const assetTypeIdTree = ref("");
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改器具台账";
    getInfo(roleObj.id);
  } else {
    assetTypeIdTree.value = searchParam.value.assetTypeId;
    console.log(assetTypeIdTree.value);

    addDialog.title = "新增器具台账";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开资产台账表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "器具台账详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
    assetTypeIdTree.value = "";
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await request({
      url: `/eam/mtAssetInfo/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}

/** 选择组织机构并赋值id  start **/
function getSelectIds(ids: [] | string, item: string) {
  if (item == "使用部门") {
    searchParam.value.usingDepartmentId = ids;
  } else if (item == "管理部门") {
    searchParam.value.manageDepartmentId = ids;
  }
}
const dataObject = (item: string) => {
  return {
    name: item == "使用部门" ? "使用部门" : "管理部门",
    defaultProps: {
      children: "nodes",
      label: "organizationName",
      value: "id",
    },
    api: "/system/sysOrganization/getUsableTree",
  };
};

// 获取位置信息下拉树
const locationInfoTree = ref([]);
const getLocationInfoTree = async () => {
  const { data } = await request({
    url: "/eam/locationInfo/getTree",
    method: "POST",
    data: {
      enabled: 1,
    },
  });
  locationInfoTree.value = data;
};
// 获取制造工厂列表
const makerList: any = ref([]);
const getMakerList = async () => {
  request({
    url: `/eam/eammaker/getList`,
    method: "post",
    data: {},
  })
    .then((res) => {
      makerList.value = res.data;
    })
    .catch((res) => {
      console.log(res);
    });
};

// 处理时间
function getcreateTime(data: any) {
  if (data) {
    searchParam.value.nextCheckDateStart = data[0];
    searchParam.value.nextCheckDateEnd = data[1];
  } else {
    searchParam.value.nextCheckDateStart = "";
    searchParam.value.nextCheckDateEnd = "";
  }
}
onMounted(() => {
  getLocationInfoTree();
  getMakerList();
});

// 导入excel
const uploadApi = "/eam/mtAssetInfo/upload";
const excelBox = ref(false);
const uploadBtn = ref(false);
const uploadFile = ref("");
const fileName = ref("");
const uploadKey = ref(Math.random());

function excelBoxOpen() {
  excelBox.value = true;
}

function getfilepath(e: any) {
  const file = e.target.files[0];
  fileName.value = file.name;
  uploadFile.value = file;
  uploadBtn.value = false;
}

function upload() {
  if (!uploadFile.value) {
    ElMessage({
      type: "warning",
      message: "请选择文件！",
    });
    return;
  }

  let formdata = new FormData();
  formdata.append("file", uploadFile.value);
  let config = { headers: { "Content-Type": "multipart/form-data" } };
  request
    .post(uploadApi, formdata, config)
    .then(({ data }) => {
      if (data !== null) {
        if (data.status === "success") {
          ElMessage({
            type: "success",
            message: "上传成功！",
          });

          closeImportDialog();
          search();
        } else if (data.status === "error") {
          ElMessage({
            type: "error",
            message: "上传失败！",
          });
          resultModel.value = true;
          msgTableData.value = data.data;
          closeImportDialog();
        } else if (data.status === "warning") {
          ElMessage({
            type: "warning",
            message: "上传成功, 部分数据异常",
          });
          resultModel.value = true;
          msgTableData.value = data.data;
          closeImportDialog();
          search();
        }
      }
    })
    .catch((error) => {
      console.log(error);
    });
}

const closeImportDialog = () => {
  excelBox.value = false;
  uploadKey.value = Math.random();
  uploadFile.value = "";
};

const resultModel = ref(false);
const msgTableData = ref([]);

const closeMsgDialog = () => {
  resultModel.value = false;
  msgTableData.value = [];
};
</script>

<!-- <style lang="scss" scoped>
:deep(.el-form-item--default .el-form-item__label) {
  // width: 90px !important;
  justify-content: end !important;
  padding: 0 7px 0 0;
}
</style> -->
